<!--
 * @Author: wjk
 * @Date: 2019-12-31 15:40:51
 * @LastEditors: wangzm
 * @LastEditTime: 2020-03-07 14:34:57
 * @description: file content
 -->
<template>
  <base-page-view :class-name="'search-container ' + (showResult ? 'list-background' : '')">
    <view class="sticky-wrap">
      <view class="search-block">
        <view class="search-left">
          <search-bar
            v-if="!authFlag"
            ref="search-bar"
            :keyword="listQuery.searchKey"
            :placeholder="placeholderText"
            background="#F5F5F6"
            @change="keyChange"
            @clear="keyClear"
            @focus="fetchSuggestData"
            @search="search"
          ></search-bar>
        </view>
        <template v-if="showResult && pageType === null">
          <image v-if="goodsLayout === 'horizontal'" class="layout-icon" src="/static/images/icon/tab_horizontal.png" mode="aspectFit" @click="goodsLayout = 'vertical'" />
          <image v-else class="layout-icon" src="/static/images/icon/tab_vertical.png" mode="aspectFit" @click="goodsLayout = 'horizontal'" />
        </template>
        <view v-if="flagCancel" class="back-btn" @click="backClick">取消</view>
      </view>
      <sort-bar
        v-if="showResult"
        :sort.sync="sortQuery"
        :current-platform="currentPlatform"
        :select-products="pageType"
        :platform-list="platformList"
        @setPlatform="setPlatform"
        @change="handleSortChange"
      />
    </view>

    <template v-if="listQuery.searchKey">
      <!-- 搜索结果 -->
      <template v-if="showResult">
        <view v-if="currentPlatform === 'BX'" class="goods-list" :class="goodsLayout">
          <view v-for="(item, index) in list" :key="index" class="goods-item-container">
            <goods-item
              class-name="goods-item"
              :goods-data="item"
              :layout="goodsLayout"
              :goods-status="goodsLayout === 'vertical' ? -1 : 6"
              :image-width="goodsLayout === 'vertical' ? '100%' : '250rpx'"
              :select-products="pageType"
              image-radius="0"
              @click="itemClick($event, index)"
            ></goods-item>
          </view>
          <base-list-state :list-length="listLength" :list-query="{ page_no: listQuery.pageNo, page_size: listQuery.pageSize }" :list-state="listState" :list-empty="listEmpty" />
        </view>
        <view v-else class="tk-goods-list" :class="goodsLayout">
          <view v-for="(item, index) in list" :key="index" class="layout">
            <view class="goods-item-container" @click="handleNavigeTo(item)">
              <view class="goods-pic">
                <b-image :src="item.imageUrl" width="280" height="280" mode="aspectFit" />
              </view>
              <view class="goods-info">
                <view class="goods-title">
                  <view v-if="goodsLayout === 'vertical'" class="platform" :class="'platform-' + currentPlatform">{{ platformType[currentPlatform] }}</view>
                  {{ item.title }}
                </view>
                <view v-if="goodsLayout !== 'vertical' && currentPlatform === 'PDD'" class="goods-sales">销量{{ item.monthSales }}</view>
                <view class="goods-coup">
                  <view v-if="item.hasCoupon || item.discount" class="coupon" :style="'background-image: url(' + conpon_bg[currentPlatform] + ')'">
                    <template v-if="item.hasCoupon">{{ item.couponDiscount }}元券</template>
                    <template v-else-if="item.discount">{{ item.discount }}折</template>
                  </view>
                  <!-- <text v-if="item.hasCoupon" class="goods-coup-price">{{ item.couponDiscount }}元券</text> -->
                  <template v-if="item.commission > 0">
                    <text v-if="item.commission < 0.01" class="goods-coup-price-tip">赚0.00元</text>
                    <text class="goods-coup-price-tip">赚{{ item.commission | formatMoney }}元</text>
                  </template>
                </view>
                <view class="goods-price">
                  <text class="goods-price-num">{{ item.actualPrice }}</text>
                  <text v-if="item.hasCoupon || item.discount" class="goods-price-tip">
                    {{ currentPlatform === 'PDD' ? '券后价' : '折后价' }}
                  </text>
                </view>
                <view v-if="goodsLayout !== 'vertical'" class="goods-type">
                  <b-image v-if="currentPlatform === 'VOP'" class-name="goods-type-icon" :src="'/static/images/biHuaSuan/icon_' + currentPlatform + '.png'" mode="aspectFit" :is-asset="true" />
                  <b-image v-else class-name="goods-type-icon" :src="'/static/images/biHuaSuan/platform_' + currentPlatform + '.png'" mode="aspectFit" :is-asset="true" />
                  <text class="goods-type-txt">{{ item.shopNick }}</text>
                </view>
                <view v-if="goodsLayout === 'vertical'" class="other">
                  <view class="original-price">￥{{ item.originalPrice }}</view>
                  <view v-if="currentPlatform !== 'VOP'" class="month-sales">销量{{ item.monthSales }}</view>
                </view>
              </view>
            </view>
          </view>
          <base-list-state :list-length="listLength" :list-query="{ page_no: tKQuery.pageNum, page_size: tKQuery.pageSize }" :list-state="listState" :list-empty="listEmpty" />
        </view>
      </template>
      <!-- 搜索关联关键字-->
      <view v-else-if="keyword.suggest.length" class="keyword-suggest-list">
        <view v-for="(item, index) in keyword.suggest" :key="index" class="keyword-item" @click="keywordClick(item, 'suggest')">
          <span v-for="(sItem, sIndex) in item.split('')" :key="sIndex" :class="{ fontBold: listQuery.searchKey.indexOf(sItem) > -1 }">{{ item[sIndex] }}</span>
        </view>
      </view>
    </template>
    <view v-else class="history-list">
      <!-- 热门搜索 -->
      <view v-if="keyword.hot.length" class="keyword-block hot">
        <view class="block-title">
          <view class="sub-item">热门推荐</view>
        </view>
        <view class="block-content">
          <view v-for="(item, index) in keyword.hot" :key="index" class="keyword-item" :class="{ active: index < 3 }" @click="keywordClick(item, 'hot')">
            {{ item }}
          </view>
        </view>
      </view>
      <!-- 搜索历史 -->
      <view v-if="keyword.history.length" class="keyword-block history">
        <view class="block-title">
          <view class="sub-item">最近搜索</view>
          <image class="icon" src="/static/images/icon/icon_delete.png" mode="aspectFit" @click="clearHistory" />
        </view>
        <view class="block-content">
          <view v-for="(item, index) in keyword.history" :key="index" class="keyword-item" @click="keywordClick(item, 'history')">{{ item }}</view>
        </view>
      </view>
    </view>
    <view v-if="btnShow" class="optionProduct">
      <view class="btnBox">
        <text class="leftContent">已选商品{{ optionState.length }}件</text>
        <button type="primary" :class="{ rightBtnColor: disabled }" class="rightBtn" @click="openPublish">选好了</button>
      </view>
    </view>
  </base-page-view>
</template>

<script>
import searchBar from '@/components/searchBar/index'
import sortBar from '@/components/sortBar/index'
import goodsItem from '@/components/goodsItem/index.vue'
import { debounce } from '@/utils/tools'
import { mapState } from 'vuex'
import './index.scss'
export default {
  components: {
    searchBar,
    sortBar,
    goodsItem
  },
  data() {
    return {
      conpon_bg: {
        PDD: `${process.env.VUE_APP_IMAGE_ASSET}/images/biHuaSuan/bg_coupon_PDD.png`,
        VOP: `${process.env.VUE_APP_IMAGE_ASSET}/images/biHuaSuan/bg_coupon_VOP.png`
      },
      placeholderText: '',
      currentPlatform: 'BX',
      platformType: {
        // 平台类型
        BX: '碧选',
        PDD: '拼多多',
        VOP: '唯品会'
      },
      platformList: [],
      keyType: '', // 埋点用, history、hot、suggest
      keyword: {
        history: uni.getStorageSync('keywords') || [],
        hot: [],
        suggest: []
      },
      sortQuery: {
        all: 1,
        sales: null,
        news: null,
        price: null,
        sortValue: 'DESC'
      },
      refreshFlag: false,
      goodsLayout: 'horizontal',
      listQuery: {
        searchKey: '',
        sort: 'DESC',
        sortField: 'COMPOSITE',
        pageNo: 1,
        pageSize: 10
      },
      tKQuery: {
        keyword: '',
        sortKey: '', // 佣金：commission，销量：sales ，价格：price
        sortValue: '', // ASC 正序/ DESC 逆序
        highPrice: '',
        lowPrice: '',
        pageNum: 1,
        pageSize: 20
      },
      list: [],
      listState: {
        loading: false,
        more: true
      },
      listEmpty: { type: 'empty_search', text: '没有搜索到相关的商品' },
      showResult: false,
      authFlag: false,
      pageType: null, // 用于区别是从添加商品页面内跳转过去的
      flagCancel: true, // 是否显示右侧图标
      btnShow: false
    }
  },
  computed: {
    ...mapState(['optionState']),
    listLength() {
      // 由于微信小程序无法自动更新base-list-state组件,故采用computed
      return this.list.length
    },
    disabled() {
      return !(this.optionState.length > 0)
    }
  },
  created() {},
  onLoad(option) {
    this.pageType = option.type || null
    this.listQuery = {
      searchKey: '',
      sort: 'DESC',
      sortField: 'COMPOSITE',
      pageNo: 1,
      pageSize: 10
    }
    this.listState = {
      loading: false,
      more: true
    }
    this.list = []
    this.fetchData()
    this.fetchPlatformData()
  },
  onShow() {
    if (this.authFlag) {
      this.authFlag = false
      this.fetchGoodsData(true)
    }
  },
  onPullDownRefresh() {
    this.listQuery.pageNo = 1
    this.fetchGoodsData(true)
    this.fetchPlatformData(true)
  },
  onReachBottom: debounce(function() {
    if (this.listState.more && !this.listState.loading) {
      if (this.currentPlatform === 'BX') {
        this.listQuery.pageNo++
      } else {
        this.tKQuery.pageNum++
      }
      this.fetchGoodsData()
    }
  }, 500),
  methods: {
    openPublish() {
      if (this.optionState.length > 0) {
        uni.navigateBack({ url: '/pagesMaterial/publish/index' })
      } else {
        return false
      }
    },
    async fetchData() {
      const res = await this.$api.homeApi.getSearchKey()
      if (res.success && res.data) {
        this.placeholderText = res.data.search_backgroud
        this.keyword.hot = res.data.search_key || []
      }
    },
    async fetchPlatformData() {
      const res = await this.$api.biHuaSuanApi.getSearchPlatform()
      if (res.success && res.data) {
        this.platformList = [{ id: 1, name: '碧选', platform: 'BX' }].concat(res.data)
      }
    },
    async fetchSuggestData() {
      this.keyword.suggest = []
      this.showResult = false
      const res = await this.$api.homeApi.searchSuggest({ searchKey: this.listQuery.searchKey })
      if (res.success) {
        this.keyword.suggest = res.data || []
      }
      this.flagCancel = true
    },
    clearHistory() {
      this.$gc.$message({
        content: '确认清空历史记录?',
        title: '提示',
        confirmText: '确定',
        align: 'center',
        confirm: () => {
          this.keyword.history = []
          uni.removeStorage({ key: 'keywords' })
        }
      })
    },
    keyChange(value) {
      this.listQuery.searchKey = value
      this.tKQuery.keyword = value
      this.fetchSuggestData()
    },
    keyClear() {
      this.listQuery.searchKey = ''
      this.showResult = false
    },
    keywordClick(value, type) {
      // var itemIscheck = []
      this.listQuery.searchKey = value
      this.tKQuery.keyword = value
      this.$refs['search-bar'].setValue(value)
      this.search(type)
      if (this.pageType === 'pagesMaterial') {
        this.flagCancel = !this.flagCancel
        this.btnShow = true
      } else if (this.showResult) {
        this.flagCancel = !this.flagCancel
      }
    },
    handleSortChange({ sortQuery, tKSort }) {
      this.list = []
      this.tKQuery = {
        ...this.tKQuery,
        ...tKSort,
        platform: this.currentPlatform,
        pageNum: 1
      }
      const sortFieldObj = {
        '0000': 'LAN_PRICE', // 价格
        '0001': 'LAN_PRICE', // 价格
        '0010': 'LISTING_TIME', // 上新
        '0100': 'SALES_VOLUME', // 销量
        '1000': 'COMPOSITE' // 综合
      }
      const oldKey = `${this.sortQuery.all === null ? 0 : 1}${this.sortQuery.sales === null ? 0 : 1}${this.sortQuery.news === null ? 0 : 1}${this.sortQuery.price === null ? 0 : this.sortQuery.price}`
      const newKey = `${sortQuery.all === null ? 0 : 1}${sortQuery.sales === null ? 0 : 1}${sortQuery.news === null ? 0 : 1}${sortQuery.price === null ? 0 : sortQuery.price}`

      const sortField = sortFieldObj[newKey]
      let sort = 'DESC'
      if (oldKey === newKey) {
        sort = this.listQuery.sort === 'DESC' ? 'ASC' : 'DESC'
      } else if (sortField === 'LAN_PRICE') {
        sort = newKey === '0000' ? 'DESC' : 'ASC'
      } else {
        sort = 'DESC'
      }
      this.sortQuery = {
        ...sortQuery,
        sortValue: sort
      }
      this.listQuery = {
        ...this.listQuery,
        sort,
        sortField,
        ...sortQuery,
        pageNo: 1
      }
      for (const x in this.sortQuery) {
        if (this.sortQuery[x] === 1 || this.sortQuery[x] === 0) {
          let key_word = '综合'
          switch (x) {
            case 'all':
              key_word = '综合'
              break
            case 'news':
              key_word = '上新'
              break
            case 'sale':
              key_word = '销量'
              break
            case 'price':
              key_word = '价格'
              break
            default:
              key_word = '综合'
          }
          this.$sensorTrack('SEARCH_RESULT_STYLE', {
            page_name: 'search',
            button_name: key_word,
            key_word: this.listQuery.searchKey
          })
        }
      }
      this.fetchGoodsData()
    },
    handleNavigeTo(item) {
      this.$navigateTo(`/pagesBHS/goods/index?goodsId=${item.goodsId}&platform=${item.platform}`)
    },
    setPlatform(platform) {
      this.currentPlatform = platform
    },
    search(type) {
      if (this.listQuery.searchKey !== '') {
        this.keyType = type
        if (type === 'suggest') {
          this.$sensorTrack('SEARCH', {
            page_name: 'search',
            button_name: 'screen',
            key_word: this.listQuery.searchKey
          })
        } else if (type === 'hot') {
          this.$sensorTrack('HOT_SEARCH', {
            page_name: 'search',
            button_name: 'hot_word',
            content_name: this.listQuery.searchKey
          })
        } else if (type === 'history') {
          this.$sensorTrack('RECENT_SEARCH', {
            page_name: 'search',
            button_name: 'history_word',
            content_name: this.listQuery.searchKey
          })
        } else {
          this.$sensorTrack('SEARCH', {
            page_name: 'search',
            button_name: 'screen',
            key_word: this.listQuery.searchKey
          })
        }
        this.list = []
        this.saveSearchHistory(this.listQuery.searchKey)
        this.showResult = true
        this.listQuery.pageNo = 1
        this.listState.more = true
        this.fetchGoodsData()
      }
      // this.listQuery.searchKey = value
    },
    async fetchGoodsData(flag) {
      this.refreshFlag = !!flag
      this.listState.loading = true
      if (this.currentPlatform !== 'BX') {
        this.tKQuery.keyword = this.listQuery.searchKey
        const tKRes = await this.$api.biHuaSuanApi.getGoods(this.tKQuery)
        if (this.tKQuery.pageNum === 1) {
          this.list = []
        }
        if (tKRes.success && tKRes.data) {
          this.list = this.list.concat(tKRes.data.list || [])
          this.listState.more = tKRes.data.list && this.tKQuery.pageSize === tKRes.data.list.length
        } else if (tKRes.code === 1002 && this.currentPlatform === 'PDD') {
          this.$gc.$message({
            title: '提 示',
            content: '请先前往拼多多进行授权',
            confirmText: '去授权',
            align: 'center',
            confirm: () => {
              // #ifdef H5
              window.open(tKRes.msg, '_blank')
              this.authFlag = true
              window.addEventListener('pageshow', e => {
                this.authFlag = false
                this.fetchGoodsData(true)
              })
              // #endif

              // #ifdef MP-WEIXIN
              if (tKRes.data) {
                uni.navigateToMiniProgram({
                  appId: tKRes.data.appId,
                  path: tKRes.data.url,
                  extraData: {},
                  success: res => {
                    // 打开成功
                    this.authFlag = true
                  }
                })
              }
              // #endif
            }
          })
        }
      } else {
        const res = await this.$api.homeApi.goodsSearch(this.listQuery)
        if (this.listQuery.pageNo === 1) {
          this.list = []
        }
        if (res.success && res.data) {
          const list = (res.data.records || []).map(i => {
            return {
              ...i,
              pic: i.majorPic,
              title: i.goodsTitle,
              vip_price: i.lanPrice,
              price: i.price,
              volume: i.salesVolume,
              goods_id: i.goodsId,
              type: i.goodsType,
              from_type: 1
            }
          })
          this.list = this.list.concat(list)
          this.listState.more = this.listQuery.pageNo < res.data.pages
          this.optionState.forEach(res => {
            this.list = this.list.map(item => {
              if (res.goodsId === item.goodsId) {
                item.isCheck = true
              }
              return item
            })
          })
        }
      }
      setTimeout(() => {
        this.listState.loading = false
        this.refreshFlag = false
        uni.stopPullDownRefresh()
      }, 500)
    },
    saveSearchHistory(value) {
      const index = this.keyword.history.findIndex(i => i === value)
      if (index > -1) {
        this.keyword.history.splice(index, 1)
      }
      this.keyword.history = [value].concat(this.keyword.history)
      uni.setStorage({
        key: 'keywords',
        data: this.keyword.history
      })
    },
    itemClick(item, index) {
      this.$sensorTrack('SEARCH_RESULT', {
        page_name: 'search',
        key_word: this.listQuery.searchKey,
        content_name: item.title,
        commodity_id: item.goods_id
      })
    },
    backClick() {
      uni.navigateBack()
    }
  }
}
</script>
